import * as React from 'react';
//建立页面数据和store 的关联
import { connect } from 'react-redux'
import axios from 'axios';
import { Post, Get, Patch, Put } from '../../utils/utilHttp'
import { Link, RouteComponentProps } from 'react-router-dom';
import { Button, WhiteSpace, WingBlank } from 'antd-mobile';
import './home.scss'

import  img001 from './img/001.jpg'
import  img002 from './img/002.jpg'
import  img003 from './img/003.jpg'

interface IState {
}
interface IProps extends RouteComponentProps {
}
class Home extends React.Component<IProps, IState> {
  state = {
    isRun:false,//中间图标运动
  }
  componentDidMount() {
    this.initMap(); 
  }
  componentDidUpdate(prevProps:any, prevState:any){
    //监听当前是否登录 控制显示
    if ((this.props as any).isLogin !== (prevProps as any).isLogin) {
      if((this.props as any).isLogin){
        this.setState({
          isLogin:(this.props as any).isLogin,
          userInfo:(this.props as any).userInfo
        })
      }
    }
  }
  //封装ajax
  axiosJsonp = (url:string):any => {
    return new Promise((resolve, reject) => {
        let JSONP = document.createElement("script");
        JSONP.type = "text/javascript";
        JSONP.src = `${url}`;
        document.getElementsByTagName("head")[0].appendChild(JSONP);

        (window as any).callback = (res:any) => {
            resolve(res)
        }
        setTimeout(() => {
            document.getElementsByTagName("head")[0].removeChild(JSONP)
        }, 5000)
    })
  }
  //初始化
  initMap=()=>{
    let BMap =window.BMap;
    var map = new BMap.Map("container"); // 创建Map实例
    var point = new BMap.Point(121.501,31.236);//坐标点
    var point1 = new BMap.Point(121.501,31.337);//坐标点

    map.centerAndZoom(point, 15); // 初始化地图,设置中心点坐标和地图级别
    map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放

    map.addControl(new BMap.NavigationControl());    
    map.addControl(new BMap.ScaleControl());    
    map.addControl(new BMap.OverviewMapControl());    
    map.addControl(new BMap.MapTypeControl());    
    map.setCurrentCity("北京"); // 仅当设置城市信息时，MapTypeControl的切换功能才能可用  
    
    var marker = new BMap.Marker(point);        // 创建标注    
    map.addOverlay(marker);                     // 将标注添加到地图中 

    //点击了标注,添加一个标注
    marker.addEventListener("click", function(){    
      console.log("您点击了标注,添加一个标注");   
      var myIcon = new BMap.Icon("markers.png", 
      new BMap.Size(23, 25), {
        offset: new BMap.Size(10, 25), // 指定定位位置
        imageOffset: new BMap.Size(0, 0 - 10 * 25) // 设置图片偏移
      });
      var marker1=new BMap.Marker(point1);
      // map.removeOverlay(marker);
      map.addOverlay(marker1);
    }); 
    //地图拖拽事件
    //dragstart  dragging  dragend
    map.addEventListener("dragstart",()=>{
      this.setState({
        isRun:false
      })
    })
    map.addEventListener("dragend",()=>{
      var bs = map.getBounds();   //获取可视区域
      var bssw = bs.getSouthWest();   //可视区域左下角
      var bsne = bs.getNorthEast();   //可视区域右上角
      console.log("当前地图可视范围是：" + bssw.lng + "," + bssw.lat + "到" + bsne.lng + "," + bsne.lat);
      //计算得到中心点经纬度
      this.setState({
        isRun:true
      })
    })
    
    //添加消息提示框
    var opts = {    
      width : 250,     // 信息窗口宽度    
      height: 100,     // 信息窗口高度    
      title : "提示标题"  // 信息窗口标题   
    }    
    var infoWindow = new BMap.InfoWindow("提示内容", opts);  // 创建信息窗口对象    
    map.openInfoWindow(infoWindow, point1);      // 打开信息窗口 指向谁
    
    //新增一个地图图层
    var traffic = new BMap.TrafficLayer();        // 创建交通流量图层实例      
    map.addTileLayer(traffic);                    // 将图层添加到地图上
    
    //路线规划
    var driving = new BMap.DrivingRoute(map, { 
      renderOptions: { 
        map: map, 
        autoViewport: true 
      } 
    });
    var start = point;
    var end = point1;

    // setTimeout(() => {
    //   driving.search(start, end);
    // }, 5000);

    //添加全景功能
    var stCtrl = new BMap.PanoramaControl();  
    stCtrl.setOffset(new BMap.Size(20, 20));  
    map.addControl(stCtrl);
    
    //定位
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition((r:any)=>{
      console.log(r);
      if(geolocation.getStatus() == "0"){
        //已经获得经纬度
        //alert('您的位置：'+r.point.lng+','+r.point.lat);

        //经纬度转地址
        var myGeo = new BMap.Geocoder();      
        // 根据坐标得到地址描述    
        myGeo.getLocation(new BMap.Point(r.point.lng, r.point.lat), function(result:any){      
          if (result){      
          // alert(result.address);
          let point = new BMap.Point(r.point.lng,r.point.lat)
          let marker = new BMap.Marker(point);        // 创建标注    
          map.addOverlay(marker);           
          }      
        });

        //调接口获取精确经纬度(好像没什么卵用)
        this.axiosJsonp(`http://api.map.baidu.com/reverse_geocoding/v3/?ak=2Ro4FB4Y8c8od4iHlaGGLWxTiDHfQHZY&output=json&coordtype=wgs84ll&location=${r.point.lat},${r.point.lng}&callback=callback`)
        .then((res:any)=>{
          let resObj=res;
          // console.log(resObj);
          if(resObj.status==0){
            // alert(resObj.result.formatted_address)
            // alert(resObj.result.location.lng)
            setTimeout(() => {
              let point = new BMap.Point(resObj.result.location.lng,resObj.result.location.lat)
              let marker = new BMap.Marker(point);        // 创建标注    
              map.addOverlay(marker);                     // 将标注添加到地图中 
            }, 5000);
          }
        })
      } else {
        console.log('failed'+geolocation.getStatus());
      }        
    });
  }

  render() {
    let { isRun }=this.state;
    return (
      <div className='home_box'>
        <div className='home_top'></div>
        <div className='home_main' style={{position: 'fixed',top: '1rem',left: 0,right: 0,bottom: 0}}>
          <div className='container' id='container'></div>
          <div className='center_icon_box'>
            <i className={`icon icon_xiafan center_icon ${isRun?'run':''}`}></i>
          </div>
        </div>
      </div>
    )
  }
}


//将store里面的数据映射到props 这个数据
//就是取store的数据 然后操作 赋值给页面的变量
//将页面数据和全局数据绑定
const mapState = ({ store }: any) => {
  return ({
    isLogin: store.isLogin,
    userInfo:store.userInfo
  })
}

const mapDispatch = ({ store }: any) => ({
  // changeLoaderType() {
  //   store.changeLoaderType(true)
  // }
  setPlayListAct(data:any){
    store.setPlayListAct(data)
  },
  setMp3ListAct(data:any){
    store.setMp3ListFun(data)
  },
})
//返回了 connect 其实是一个容器组件
export default connect(mapState, mapDispatch)(Home); 
